/*
 * @Description: 元数据上下文
 * @Author: Rfan
 * @Date: 2022-05-30 14:43:58
 * @LastEditTime: 2022-09-08 15:02:24
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message, Modal } from 'antd';
import {
  ADD_RELY,
  DELETE_RELY,
  EDIT_RELY,
  SET_RELY_LIST,
  SET_METADATA_LIST,
  SET_SELECTED_ITEM,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_LEVEL
} from '../constants';
import { MetadataRelyReducer } from '../reducers/MetadataRelyReducer';
import { addRely, deleteRely, editRely, fetchMetadata, fetchRelyListByPage } from '@/api/metadata';
import { selectItemByKey } from '@/utils/list';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectLevel: {},

  // 所有层级的元数据
  levelMatedata: {},
  // 元数据依赖列表
  inheritList: [],
  // 选中的表格条目
  selectItems: [],

  // -------- 字典 --------
  // 依赖规则状态
  stateList: [
    { id: 0, name: '有效', color: 'blue' },
    { id: 1, name: '无效', color: 'red' }
  ]
};

const MetadataRelyContext = createContext();

const MetadataRelyContextProvider = (props) => {
  const [state, dispatch] = useReducer(MetadataRelyReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的层级
     */
    setSelectLevel(data) {
      dispatch({ type: SET_SELECT_LEVEL, data });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 请求级别元数据列表方法
     * @param {object} level 请求的层级
     * @return {*}
     */
    getLevelMetadata(level) {
      return new Promise((resolve, reject) => {
        // 如果已有该层级元数据，直接返回
        if (state.levelMatedata[level] && state.levelMatedata[level].length > 0) {
          resolve(state.levelMatedata[level]);
        } else {
          const fieldQuery = {
            metadataFieldType: QUERY_METADATA_ALL,
            coordinate: {
              atType: state.selectAT?.atType,
              atCode: state.selectAT?.atCode,
              level
            }
          };
          fetchMetadata(fieldQuery)
            .then((res) => {
              const { data } = res;
              dispatch({ type: SET_METADATA_LIST, data, level });
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },

    /**
     * @description: 分页获取依赖列表
     * @param {*} params 请求参数
     */
    getRelyList(params) {
      return new Promise((resolve, reject) => {
        fetchRelyListByPage(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_RELY_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 添加元数据依赖条目
     * @param {*} params 添加的条目信息
     */
    addRelyFunc(params) {
      return new Promise((resolve, reject) => {
        addRely(params)
          .then((res) => {
            message.success('增加成功');
            const { data } = res;
            dispatch({ type: ADD_RELY, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 添加元数据依赖条目
     * @param {*} params 添加的条目信息
     */
    editRelyFunc(params) {
      return new Promise((resolve, reject) => {
        editRely(params)
          .then((res) => {
            message.success('编辑成功');
            const { data } = res;
            dispatch({ type: EDIT_RELY, data, id: data.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    deleteRelyFunc(id, content = '确认删除该依赖配置？') {
      Modal.confirm({
        title: '删除',
        content,
        onOk() {
          const ids = Array.isArray(id) ? id.join(',') : id;
          deleteRely(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_RELY, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },

    /**
     * @description: 讲依赖规则处理为字符串形式
     * @param {[]} ruleArray
     * @return {*}
     */
    generateRule(ruleArray) {
      return ruleArray
        .map((rule) => {
          const { type, fieldValue, strValue } = rule;
          if (type === 1) {
            const levelItem = selectItemByKey(fieldValue?.level, state.selectAT.levelList, 'level');
            return `[${levelItem.levelName}:${fieldValue.field_desc}]`;
          }
          return strValue;
        })
        .join('');
    }
  };

  const filters = {
    stateNameFilter(id) {
      return state.stateList.find((item) => item.id === id)?.name || '-';
    },
    stateColorFilter(id) {
      return state.stateList.find((item) => item.id === id)?.color || '-';
    }
  };

  // watch listQuery来加载列表
  useEffect(() => {}, []);

  return (
    <MetadataRelyContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </MetadataRelyContext.Provider>
  );
};

export const useMetadataRelyContext = () => {
  return useContext(MetadataRelyContext);
};

export { MetadataRelyContext, MetadataRelyContextProvider };
